package com.kkd.kkdapp.db.base;

import java.lang.reflect.Field;

import com.kkd.kkdapp.db.annotate.EADBField;
import com.kkd.kkdapp.db.annotate.EADBField.EADBFieldMode;
import com.kkd.kkdapp.db.annotate.EADBField.EADBFieldType;
import com.kkd.kkdapp.utils.LogUtil;

import android.content.ContentValues;


/**
 * sql语句生产者<br>
 * 
 * <b>创建时间</b> 2014-10-31
 * 
 * @author askzhao
 * 
 * @version 1.0
 */
public class SqlBuilder {
	
	private static final String TAG = SqlBuilder.class.getSimpleName();

	private static final String INSERT = "INSERT ";

	/**
	 * 根据java对象创建表
	 * 
	 * @param tableClass
	 * @return
	 */
	public static String getCreateTableSql(Class<?> tableClass) {
		String tableName = tableClass.getSimpleName();
		Field[] fs = EATool.getField(tableClass);
		EADBField[] ans = EATool.getEADBField(fs);

		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < ans.length; i++) {
			Field tF = fs[i];
			EADBField tA = ans[i];

			EADBFieldType type = tA.type();
			EADBFieldMode[] model = tA.mode();

			boolean isKey = false;
			boolean isUnique = false;
			boolean notNull = false;
			for (int j = 0; j < model.length; j++) {
				EADBFieldMode t = model[j];
				if (t == EADBFieldMode.Key) {
					isKey = true;
				} else if (t == EADBFieldMode.Unique) {
					isUnique = true;
				} else if (t == EADBFieldMode.NotNull) {
					notNull = true;
				}
			}

			// 优先选择注解的fieldName,如果为空选择属性名为字段
			String fieldNameInDB = "".equals(tA.fieldName()) ? tF.getName()
					: tA.fieldName();
			// 正确设置类型
			String fieldTypeInDB = EADBFieldType.Default == type ? "" : type
					.toString();
			String fieldIsKey = isKey ? " INTEGER PRIMARY KEY" : "";
			String fieldIsUnique = isUnique ? " UNIQUE" : "";
			String fieldAllowNull = notNull ? " NOT NULL" : "";

			String partSql = String.format("%s %s%s%s%s", fieldNameInDB,
					fieldTypeInDB, fieldIsKey, fieldIsUnique, fieldAllowNull);
			sb.append(partSql + ((i + 1) == ans.length ? "" : ","));
		}

		String createTableSql = String.format(
				"CREATE TABLE IF NOT EXISTS %s(%s);", tableName, sb);

		LogUtil.d(TAG, "create table sql:" + createTableSql);

		return createTableSql;
	}

	/**
	 * 删除表sql
	 * 
	 * @param tableClass
	 * @return
	 */
	public static String getDropTableSql(Class<?> tableClass) {
		String dropTableSql = "DROP TABLE IF EXISTS "
				+ tableClass.getSimpleName() + ";";
		LogUtil.d(TAG, "drop table sql:" + dropTableSql);
		return dropTableSql;
	}

	public static String[] getColumns(Class<?> clazz) {
		Field[] fs = EATool.getField(clazz);
		EADBField[] ans = EATool.getEADBField(fs);
		String[] columns = new String[ans.length];
		for (int i = 0; i < ans.length; i++) {
			Field tF = fs[i];
			EADBField tA = ans[i];
			// 优先选择注解的fieldName,如果为空选择属性名为字段
			String fieldNameInDB = "".equals(tA.fieldName()) ? tF.getName()
					: tA.fieldName();
			columns[i] = fieldNameInDB;
		}
		return columns;
	}

	public static ContentValues getContentValuesByObj(Object entity) {
		ContentValues values = new ContentValues();
		Field[] fs = EATool.getField(entity.getClass());
		EADBField[] ans = EATool.getEADBField(fs);
		for (int i = 0; i < ans.length; i++) {
			Field tF = fs[i];
			EADBField tA = ans[i];
			if (EATool.isKeyField(tA))
				continue;
			Object val = null;
			try {
				val = tF.get(entity);
			} catch (Exception e) {
				LogUtil.exception(e);
			}
			// 优先选择注解的fieldName,如果为空选择属性名为字段
			String fieldNameInDB = "".equals(tA.fieldName()) ? tF.getName()
					: tA.fieldName();
			if (null != val) {
				if(tF.getType() == Boolean.class || tF.getType() == boolean.class){
					values.put(fieldNameInDB, ((Boolean)val == true)?"true":"false");
				}else{
					values.put(fieldNameInDB, val.toString());
				}
			}
		}
		return values;
	}

	/**
	 * 获取插入语句
	 * 
	 * @param entity
	 * @param 是否包含主键key
	 * @return
	 */
	public static String getInsertSql(Object entity, boolean hasKey) {
		Field[] fs = EATool.getField(entity.getClass());
		EADBField[] ans = EATool.getEADBField(fs);
		StringBuilder column = new StringBuilder();
		StringBuilder values = new StringBuilder();
		for (int i = 0; i < ans.length; i++) {
			Field tF = fs[i];
			EADBField tA = ans[i];

			if (!hasKey && EATool.isKeyField(tA))
				continue;
			Object val = null;
			try {
				val = tF.get(entity);
			} catch (Exception e) {
				LogUtil.exception(e);
			}
			// 优先选择注解的fieldName,如果为空选择属性名为字段
			String fieldNameInDB = "".equals(tA.fieldName()) ? tF.getName()
					: tA.fieldName();
			values.append(val).append(",");
			column.append(fieldNameInDB).append(",");
		}
		if (column.length() > 0) {
			column = column.delete(column.length() - 1, column.length());
		}
		if (values.length() > 0) {
			values = values.delete(values.length() - 1, values.length());
		}
		StringBuilder sql = new StringBuilder();
		sql.append(INSERT);
		sql.append(" INTO ");
		sql.append(entity.getClass().getSimpleName());
		sql.append(" (");
		sql.append(column);
		sql.append(")");
		sql.append(" VALUES(");
		sql.append(values);
		sql.append(");");
		// LogUtil.d(TAG, "insert table sql:" + sql.toString());
		return sql.toString();
	}
}
